package cn.itcast.servlet;

import cn.itcast.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/listStudentServlet")
public class ListStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //读取文件
        BufferedReader br = new BufferedReader(new FileReader("D:/stu.txt"));

        //创建集合，保存学生对象
        ArrayList<Student> list = new ArrayList<>();

        //循环读取，封装，添加
        String line;
        while ((line=br.readLine())!=null){
            Student stu = new Student();
            String[] arr = line.split(",");
            stu.setUsername(arr[0]);
            stu.setAge(arr[1]);
            stu.setScore(arr[2]);
            list.add(stu);
        }

        //遍历集合，响应
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        for (Student s : list) {
            pw.write(s.getUsername()+" "+s.getAge()+" "+s.getScore());
            pw.write("<br/>");
        }

    }
}
